<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-客户档案`"
		width="500px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="编号">
						<el-input v-model="ruleForm.code" disabled placeholder="系统自动生成" />
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="名称" prop="name">
						<el-input v-model="ruleForm.name" placeholder="名称" />
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="识别码">
						<el-input v-model="ruleForm.CIN" placeholder="识别码" />
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="所在地">
						<div class="flex-start-center">
							<jk-select v-model="ruleForm.provinceId" :option-list="provinceList" label-key-name="province" size="medium" placeholder="所在省份" @change="onProvinceChange" />
							<jk-select v-model="ruleForm.cityId" :option-list="cityList" label-key-name="city" size="medium" placeholder="所在城市" />
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="客户等级">
						<el-select v-model="ruleForm.customerLevel" class="width-100-percent" placeholder="客户等级">
							<el-option
								v-for="item in customerLevelList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="客户地址">
						<el-input v-model="ruleForm.address" type="textarea" :row="2" placeholder="客户地址" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import {
        spinCustomerCreate,
        spinCustomerUpdate,
        spinCustomerGet
    } from '../../../api/personnel/customer';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    import { devopsProvinceList } from '../../../api/commont';
    export default {
        name: 'Customer',
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                cityList: [],
                provinceList: [],
                customerLevelList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    code: '',
                    name: '',
                    auditState: 1,
                    provinceId: null,
                    cityId: null,
                    customerLevel: null,
                    customerLevelName: '',
                    address: '',
                    CIN: null
                },
                rules: {
                    code: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onProvinceChange() {
                this.$set(this.ruleForm, 'cityId', null);
                this.$set(this.ruleForm, 'cityName', null);
                this.cityList = [];
                this.getCityListRequest();
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                params.provinceName = this.provinceList.find(x => x.id === params.provinceId) ? this.provinceList.find(x => x.id === params.provinceId).province : '';
                params.cityName = this.cityList.find(x => x.id === params.cityId) ? this.cityList.find(x => x.id === params.cityId).city : '';
                if (params.customerLevel) params.customerLevelName = this.customerLevelList.find(x => x.id === params.customerLevel).name;
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                // 新增
                if (!this.dataId) {
                    this.ruleForm.id = null;
                    spinCustomerCreate(this.getParamData()).then(res => {
                        this.saveBtnLoading = false;
                        if (res.data.status === 200) {
                            this.$tipsBar(this, 'save');
                            // 返回id,在远程搜索组件需要使用
                            this.$emit('on-finish', res.data.res);
                        }
                    });
                    return;
                }

                // 编辑
                spinCustomerUpdate(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        // 返回id,在远程搜索组件需要使用
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinCustomerGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getCustomerLevelListRequest() {
                return systemBusinessDictPage({ categoryCode: 'CUSTOMER_LEVEL' }).then(res => {
                    if (res.data.status === 200) {
                        this.customerLevelList = res.data.res;
                    }
                });
            },
            getCityListRequest() {
                this.cityList = [];
                if (this.ruleForm.provinceId) {
                    return devopsProvinceList({
                        parentId: this.ruleForm.provinceId
                    }).then(res => {
                        if (res.data.status === 200) {
                            this.cityList = res.data.res;
                        }
                    });
                }
            },
            getProvinceListRequest() {
                return devopsProvinceList().then(res => {
                    if (res.data.status === 200) {
                        this.provinceList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                if (this.dataId) await this.getDetailRequest();
                await this.getProvinceListRequest();
                if (this.ruleForm.provinceId) await this.getCityListRequest();
                await this.getCustomerLevelListRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
